import React, { Component } from 'react'
import {
  StyleSheet,
  Text,
  View,
  Image,
  Dimensions,
  ListView,
  TextInput,
  AlertIOS,
  ProgressViewIOS,
  ActivityIndicator,
  TouchableOpacity,
  Modal
} from 'react-native'
import Video from 'react-native-video'
import Icon from 'react-native-vector-icons/Ionicons'
import Button from 'react-native-button'
import request from '../common/request'
import { api } from '../common/config'

const width = Dimensions.get('window').width
let ds = new ListView.DataSource({
  rowHasChanged: (r1, r2) => r1 !== r2
})

let comments = {
  nextPage: 0,
  data: [],
  total: 0
}


class Detail extends Component {
  constructor(props) {
    super(props)
    let video = this.props.video

    this.state = {
      video: video,

      // video loads
      videoLoaded: false,
      playing: false,
      paused: false,
      videoOk: true,
      videoProgess: 0.01,
      videoTotal: 0,
      currentTime: 0,
      // video player
      rate: 1,
      muted: false,
      resizeMode: 'contain',
      repeat: false,

      // comments
      dataSource: ds.cloneWithRows([]),
      isLoadingTail: false,
      isSending: false,
      commentText: '',

      // modal
      animationType: 'none',
      modalVisible: false
    }
  }

  componentDidMount() {
    this._fetchComments(1)
  }

  _fetchComments(page) {
    const url = api.base + api.comments

    request.get(url, { page: page })
      .then(data => {
        if (data && data.success) {
          if (data.data && data.data.length > 0) {
            comments.data = [...comments.data, ...data.data]
            ++comments.nextPage
            comments.total = data.total

            this.setState({
              dataSource: ds.cloneWithRows(comments.data)
            })

          }
        }
      })
      .catch(error => {
        console.warn(error)
      })

  }

  _focus() {
    this._setModalVisible(true)
  }

  _closeModal() {
    this._setModalVisible(false)
  }

  _setModalVisible(isVisible) {
    this.setState({
      modalVisible: isVisible
    })
  }

  _submit() {
    if (!this.state.commentText) {
      return AlertIOS.alert('留言不能为空！')
    }

    if (this.state.isSending) {
      return AlertIOS.alert('正在提交中！')
    }

    this.setState({
      isSending: true
    }, () => {
      const url = api.base + api.creationsComment
      const body = {
        accessToken: 'abcd',
        creation: '1234',
        content: this.state.commentText
      }

      request.post(url, body)
        .then(data => {
          if (data && data.success) {
            comments.data = [{
              _id: data._id,
              content: data.content,
              replyBy: data.replyBy
            }, ...comments.data]

            this._setModalVisible(false)

            this.setState({
              commentText: '',
              isSending: false,
              dataSource: ds.cloneWithRows(comments.data)
            })
          }
        })
        .catch(error => {
          console.warn(error)
          this.setState({
            isSending: false
          })
          this._setModalVisible(false)
          AlertIOS.alert('评论失败，请稍后再试！')
        })
    })
  }

  _renderRow(row) {
    return (
      <View key={row._id} style={styles.replyBox}>
        <Image style={styles.replyAvatar} source={{ uri: row.replyBy.avatar }}></Image>
        <View style={styles.reply}>
          <Text style={styles.replayNickname}>{row.replyBy.nickname}</Text>
          <Text style={styles.replayContent}>{row.content}</Text>
        </View>
      </View>
    )
  }

  _renderHeader() {
    let video = this.state.video

    return (
      <View style={styles.listHeader}>
        <View style={styles.infoBox}>
          <Image style={styles.avatar} source={{ uri: video.author.avatar }}></Image>
          <View style={styles.descBox}>
            <Text style={styles.nickname}>{video.author.nickname}</Text>
            <Text style={styles.title}>{video.title}</Text>
          </View>
        </View>
        <View style={styles.commentBox}>
          <View style={styles.comment}>
            <TextInput
              placeholder='评论下吧...'
              placeholderTextColor='#ddd'
              style={styles.commentContent}
              multiline={true}
              onFocus={this._focus.bind(this)} />
          </View>
        </View>

        <View style={styles.commentArea}>
          <Text style={styles.commentTitle}>精彩评论</Text>
        </View>
      </View>
    )
  }

  _renderFooter() {
    if (!this._hasMoreData()) {
      return (
        <View style={styles.loadingTip}>
          <Text style={styles.loadingText}>没有更多了</Text>
        </View>
      )
    }

    if (!this.state.isLoadingTail) {
      return <View></View>
    }

    return (
      <ActivityIndicator style={styles.loadingIcon} />
    )
  }

  _hasMoreData() {
    return comments.data.length !== comments.total
  }

  _fetchMoreData() {
    if (!this._hasMoreData() || this.state.isLoadingTail) return

    this._fetchComments(comments.nextPage)
  }

  _pop() {
    this.props.navigator.pop()
  }

  _onLoadStart() {
    console.log('load start')
  }

  _onLoad() {
    console.log('loads')
  }

  _onProgress(data) {
    if (!this.state.videoLoaded) {
      this.setState({
        videoLoaded: true
      })
    }

    let duration = data.playableDuration
    let currentTime = data.currentTime
    let percent = Number((currentTime / duration).toFixed(2))
    let newState = {
      videoTotal: duration,
      currentTime: Number(currentTime.toFixed(2)),
      videoProgess: percent
    }

    if (!this.state.videoLoaded) {
      newState.videoLoaded = true
    }

    if (!this.state.playing) {
      newState.playing = true
    }

    this.setState(newState)
  }

  _onEnd() {
    this.setState({
      videoProgess: 1,
      playing: false
    })
  }

  _onError(e) {
    this.setState({
      videoOk: false
    })
  }

  _rePlay() {
    this.ref.videoPlayer, seek(0)
  }

  _pause() {
    if (!this.state.paused)
      this.setState({
        paused: true
      })
  }

  _resume() {
    if (this.state.paused)
      this.setState({
        paused: false
      })
  }

  render() {
    let video = this.props.video

    return (
      <View style={styles.container}>
        <View style={styles.header}>
          <TouchableOpacity style={styles.backBox} onPress={this._pop.bind(this)}>
            <Icon name='ios-arrow-back' style={styles.backIcon} />
            <Text style={styles.backText}>返回</Text>
          </TouchableOpacity>
          <Text style={styles.headerTitle} numberOfLines={1}>视频详情页</Text>
        </View>
        <View style={styles.videoBox}>
          <Video
            ref='videoPlayer'
            source={{ uri: video.video }}
            style={styles.video}
            volume={5}
            paused={this.state.paused}
            rate={this.state.rate}
            muted={this.state.muted}
            resizeMode={this.state.resizeMode}
            repeat={this.state.repeat}

            onLoadStart={this._onLoadStart.bind(this)}
            onLoad={this._onLoad.bind(this)}
            onProgress={this._onProgress.bind(this)}
            onEnd={this._onEnd.bind(this)}
            onError={this._onError.bind(this)} />

          {
            !this.state.videoOk && <Text style={styles.failText}>视频出错了！很抱歉</Text>
          }

          {
            !this.state.videoLoaded && <ActivityIndicator
              color='#ee735c' style={styles.loadingVideoIcon} />
          }

          {
            this.state.videoLoaded && !this.state.playing
              ? <Icon
                name='ios-play'
                size={48}
                style={styles.playIcon}
                onPress={this._rePlay} />
              : null
          }

          {
            this.state.videoLoaded && this.state.playing
              ? (<TouchableOpacity
                onPress={this._pause.bind(this)}
                style={styles.pauseBtn}>
                {
                  this.state.paused
                    ? <Icon
                      onPress={this._resume.bind(this)}
                      name='ios-play'
                      size={48}
                      style={styles.resumeIcon} />
                    : <Text></Text>
                }
              </TouchableOpacity>)
              : null
          }

          <ProgressViewIOS
            style={styles.progressView}
            progressTintColor="#ee753c"
            progress={this.state.videoProgess} />
        </View>

        <ListView
          dataSource={this.state.dataSource}
          renderRow={this._renderRow.bind(this)}
          renderHeader={this._renderHeader.bind(this)}
          renderFooter={this._renderFooter.bind(this)}
          onEndReached={this._fetchMoreData.bind(this)}
          onEndReachedThreshold={20}
          enableEmptySections={true}
          showsVerticalScrollIndicator={false}
          automaticallyAdjustContentInsets={false}
        />

        <Modal
          visible={this.state.modalVisible}>
          <View style={styles.modalContainer}>
            <Icon
              onPress={this._closeModal.bind(this)}
              name='ios-close'
              style={styles.closeIcon} />
            <View style={styles.commentBox}>
              <View style={styles.comment}>
                <TextInput
                  placeholder='评论下吧...'
                  placeholderTextColor='#ddd'
                  style={styles.commentContent}
                  multiline={true}
                  defaultValue={this.state.commentText}
                  onChangeText={text => {
                    this.setState({
                      commentText: text
                    })
                  }}
                />
              </View>
            </View>
            <Button style={styles.submitBtn} onPress={this._submit.bind(this)}>评论</Button>
          </View>
        </Modal>
      </View >
    )
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#f5fcff'
  },

  header: {
    flexDirection: 'row',
    justifyContent: 'center',
    alignItems: 'center',
    width: width,
    height: 64,
    paddingTop: 20,
    paddingLeft: 10,
    paddingRight: 10,
    borderBottomWidth: 1,
    borderColor: 'rgba(0,0,0,0.1)',
    backgroundColor: '#fff'
  },

  backBox: {
    position: 'absolute',
    left: 12,
    top: 32,
    width: 50,
    flexDirection: 'row',
    alignItems: 'center'
  },

  backIcon: {
    color: '#999',
    fontSize: 20,
    marginRight: 5
  },

  backText: {
    color: '#999'
  },

  headerTitle: {
    width: width - 120,
    textAlign: 'center'
  },

  videoBox: {
    width: width,
    height: 240,
    backgroundColor: '#000'
  },

  video: {
    width: width,
    height: 240,
    backgroundColor: '#000'
  },

  loadingVideoIcon: {
    position: 'absolute',
    left: 0,
    top: 80,
    width: width,
    alignSelf: 'center',
    backgroundColor: 'transparent'
  },

  playIcon: {
    position: 'absolute',
    top: 80,
    left: width / 2 - 30,
    width: 60,
    height: 60,
    paddingTop: 6,
    paddingLeft: 24,
    backgroundColor: 'transparent',
    borderColor: '#fff',
    borderWidth: 1,
    borderRadius: 30,
    color: '#ed7b66'
  },

  pauseBtn: {
    position: 'absolute',
    left: 0,
    top: 0,
    width: width,
    height: 360
  },

  resumeIcon: {
    position: 'absolute',
    top: 80,
    left: width / 2 - 30,
    width: 60,
    height: 60,
    paddingTop: 6,
    paddingLeft: 24,
    backgroundColor: 'transparent',
    borderColor: '#fff',
    borderWidth: 1,
    borderRadius: 30,
    color: '#ed7b66'
  },

  failText: {
    position: 'absolute',
    left: 0,
    top: 110,
    width: width,
    textAlign: 'center',
    color: '#fff'
  },

  listHeader: {
    width: width,
    marginTop: 10
  },

  commentBox: {
    marginTop: 10,
    marginBottom: 10,
    padding: 8,
    width: width
  },

  commentContent: {
    paddingLeft: 10,
    color: '#333',
    borderWidth: 1,
    borderColor: '#ddd',
    borderRadius: 4,
    fontSize: 14,
    height: 80
  },

  commentArea: {
    width: width,
    paddingBottom: 10,
    paddingLeft: 10,
    paddingRight: 10,
    borderBottomWidth: 1,
    borderBottomColor: '#eee'
  },

  infoBox: {
    width: width,
    flexDirection: 'row',
    justifyContent: 'center',
    marginTop: 10
  },

  avatar: {
    width: 60,
    height: 60,
    marginRight: 10,
    marginLeft: 10,
    borderRadius: 30
  },

  descBox: {
    flex: 1
  },

  nickname: {
    fontSize: 18
  },

  title: {
    marginTop: 8,
    fontSize: 16,
    color: '#666'
  },

  replyBox: {
    width: width,
    flexDirection: 'row',
    justifyContent: 'flex-start',
    marginTop: 10
  },

  replyAvatar: {
    width: 40,
    height: 40,
    marginRight: 10,
    marginLeft: 10,
    borderRadius: 20
  },

  reply: {
    flex: 1
  },

  replayNickname: {
    color: '#666'
  },

  replayContent: {
    color: '#666',
    marginTop: 4
  },

  loadingTip: {

  },

  loadingText: {
    color: '#777',
    textAlign: 'center'
  },

  loadingIcon: {
    marginVertical: 20
  },

  modalContainer: {
    flex: 1,
    paddingTop: 45,
    backgroundColor: '#fff',
  },

  closeIcon: {
    alignSelf: 'center',
    fontSize: 30,
    color: '#ee753c'
  },

  submitBtn: {
    width: width - 20,
    padding: 16,
    marginLeft: 10,
    marginRight: 10,
    marginTop: 20,
    marginBottom: 20,
    borderWidth: 1,
    borderColor: '#ee753c',
    backgroundColor: '#ee753c',
    borderRadius: 4,
    color: '#fff',
    fontSize: 18
  }


})

module.exports = Detail